//
//  UISegmentedControl.swift
//  zhende
//
//  Created by 陆文宇 on 2017/6/7.
//  Copyright © 2017年 chenliang. All rights reserved.
//

import UIKit

extension UISegmentedControl {
    
    convenience init(items: [String], selectedIndex: Int, frame: CGRect = CGRect(x: 0, y: 0, width: screenWidth / 3 * 2, height: 44), font: UIFont = titleFont, fontColor: UIColor = UIColor.white) {
        self.init(items: items)
        
        self.frame = frame
        selectedSegmentIndex = selectedIndex
        tintColor = .clear
        setTitleTextAttributes([NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: fontColor], for: .normal)
        setTitleTextAttributes([NSAttributedStringKey.foregroundColor: mainColor], for: .selected)
        
        let itemWidth = frame.width / CGFloat(items.count)
        let lineWidth = (items[selectedIndex] as NSString).boundingRect(with: CGSize(width: itemWidth, height: frame.height), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil).width + 10
        
        let underline = UIView(frame: CGRect(x: itemWidth * CGFloat(selectedIndex) + (itemWidth - lineWidth) / 2, y: frame.height - 2, width: lineWidth, height: 2))
        underline.tag = 12
        underline.backgroundColor = mainColor
        addSubview(underline)
        addTarget(self, action: #selector(yy_changeItem(sender:)), for: .valueChanged)
    }
    
    @objc func yy_changeItem(sender: UISegmentedControl) {
        guard sender.selectedSegmentIndex >= 0 else {
            return
        }
        
        let itemWidth = frame.width / CGFloat(sender.numberOfSegments)
        let lineWidth = (sender.titleForSegment(at: sender.selectedSegmentIndex)! as NSString).boundingRect(with: CGSize(width: 80, height: 44), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: titleFont], context: nil).width + 10
        let underline = sender.subviews.flatMap { (view) -> UIView? in
            if view.tag == 12 {
                return view
            } else {
                return nil
            }
        }.last!
        
        UIView.animate(withDuration: 0.3, animations: { 
            underline.frame = CGRect(x: itemWidth * CGFloat(sender.selectedSegmentIndex) + (itemWidth - lineWidth) / 2, y: sender.frame.height - 3, width: lineWidth, height: 3)
        })
    }
}
